import urllib
import importlib, sys
importlib.reload(sys)
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfdevice import PDFDevice
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed



class PdfToWord(object):
    def __init__(self, *args, **kwargs):
        self.pdf_file = r'./Python研究者.pdf'
        self.word_file = r'D:/合胜/测试python/pdf_to_word/pdf_to_word.docx'
    
    def word(self):
        with open(self.pdf_file, 'rb') as pdf_html:
            parser = PDFParser(pdf_html)
        doc = PDFDocument()
        parser.set_document(doc)
        doc.set_parser(parser)
        doc.initialize()
        if not doc.is_extractable:
            raise PDFTextExtractionNotAllowed
        else:
            rsrcmagr = PDFResourceManager()
            laparams = LAParams()
            device = PDFPageAggregator(rsrcmagr, laparams=laparams)
            interpreter = PDFPageInterpreter(rsrcmagr, device)
            for page in doc.get_pages():
                interpreter.process_page(page)
                layout = device.get_result()
                for x in layout:
                    try:
                        if(isinstance(x, LTTextBoxHorizontal)):
                            with open(self.word_file, 'a') as f:
                                result = x.get_text()
                                print(result)
                                f.write(result + '\n')
                    except:
                        print('Failed')
                
                

if __name__ == "__main__":
    ptw = PdfToWord()
    ptw.word()